﻿using GYCTOAManagementSystemNewApi.Model;
using GYCTOAManagementSystemNewApi.Model.Enum;
using GYCTOAManagementSystemNewApi.Model.Tool;
using GYCTOAManagementSystemNewApi.Public;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace GYCTOAManagementSystemNewApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PerformanceExamineController : Controller
    {
        //DBContext _db;
        //public PerformanceExamineController(DBContext db)
        //{
        //    _db = db;
        //}
        ///// <summary>
        ///// 首页数据接口
        ///// </summary>
        ///// <returns></returns>
        //public JsonResult ExamineById()
        //{
        //    int performancessummaryid, performancesExamineid = 0;
        //    List<Performances> performances = PerformancesListControl();
        //    //总结表数据
        //    List<Performances> performancessummary = (List<Performances>)performances.Where(x => x.type == 2).ToList();
        //    //绩效考核表数据
        //    List<Performances> performancesExamine = (List<Performances>)performances.Where(x => x.type == 4).ToList();
        //    //总结表
        //    Ispanding(performancessummary, out performancessummaryid);
        //    //绩效考核表
        //    Ispanding(performancesExamine, out performancesExamineid);

        //    return Json(new { performancessummaryid = performancessummaryid, performancesExamineid = performancesExamineid });
        //}
        ///// <summary>
        ///// 获取所有的展示数据
        ///// </summary>
        ///// <returns></returns>
        //public List<Performances> PerformancesListControl()
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    int Userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    int id  = Userid;
        //    var obj = _db.Users.Where(l => l.Id == id).FirstOrDefault();
        //    PublicTool p = new PublicTool();
        //    var roles = _db.Role.ToList().Where(x => p.Compare(obj.RoleId, x.Id)).Select(x => x.RoleNumber).ToList();

        //    string rolestr = string.Empty;
        //    foreach (var item in roles)
        //    {
        //        rolestr += item;
        //    }

        //    List<Performances> PerformancesList = new List<Performances>();

        //    if (rolestr.Contains("Admin"))
        //    {
        //        //除计划表的所有表
        //        var PerformanceslistAdmin = _db.Performances.Where(x => x.type != 1).ToList();
        //        foreach (var item in PerformanceslistAdmin)
        //        {
        //            PerformancesList.Add(item);
        //        }
        //        PerformancesList = Unino.ListRepetitionPerformances(PerformancesList);

        //    }
        //    //运营综合部
        //    if (rolestr.Contains(ModuleAuthorityCode.OperationPerformanceManagement.ToString()))
        //    {
        //        //获取所有的绩效表不包括现场表(高层表)
        //        var PerformanceslistAdmin = _db.Performances.Where(x => x.State >= 1 && x.type != 1).OrderBy(x => x.PerformanceDataTime).ToList();
        //        foreach (var item in PerformanceslistAdmin)
        //        {
        //            PerformancesList.Add(item);
        //        }
        //    }
        //    //项目部负责人
        //    var ProjectListold = _db.Project.Where(z => z.HeadUserId == Userid.ToString() && z.Delete != true).ToList();
        //    var ProjectList = new List<Project>();
        //    for (int i = 0; i < ProjectListold.Count; i++)
        //    {
        //        DateTime.TryParse(ProjectListold[i].InFaceFinishDate.ToString(), out DateTime dt);
        //        if (dt.AddMinutes(1).Month == DateTime.Now.Month || ProjectListold[i].InFaceFinishDate.ToString() == "")
        //        {
        //            ProjectList.Add(ProjectListold[i]);
        //        }
        //    }

        //    if (ProjectList.Count > 0)
        //    {
        //        var arr = ProjectList.Where(x => !string.IsNullOrEmpty(x.MemberId)).Select(x => x.MemberId).ToList();
        //        string MemberId = string.Join(",", arr);
        //        if (MemberId != "")
        //        {
        //            var ProjectInfoList = _db.Performances.FromSqlRaw($"SELECT * FROM `performances` WHERE PerformanceUserID in({MemberId}) and TableType=4 and type!=1  ORDER BY PerformanceDataTime DESC").ToList();
        //            //排除成员也是项目负责人的情况
        //            var projs = _db.Project.Where(x => x.Delete != true).Select(x => x.HeadUserId).ToList();
        //            string projsid = string.Join(",", projs);
        //            ProjectInfoList = (List<Performances>)ProjectInfoList.Where(a => !(stringtoints(projsid)).Contains(a.PerformanceUserID)).ToList();
        //            foreach (var itemz in ProjectInfoList)
        //            {
        //                PerformancesList.Add(itemz);
        //            }
        //        }
        //    }
        //    //权限一150406(总结表和绩效表)
        //    if (rolestr.Contains(ModuleAuthorityCode.SitePerformanceJudgment1.ToString()))
        //    {
        //        var PerformanceslistAdmin = _db.Performances.Where(x => x.type != 1 && x.State >= 1 && x.TableType == 4).OrderBy(x => x.PerformanceDataTime).ToList();
        //        foreach (var item in PerformanceslistAdmin)
        //        {
        //            PerformancesList.Add(item);
        //        }
        //    }
        //    //权限二150407
        //    if (rolestr.Contains(ModuleAuthorityCode.SitePerformanceJudgment2.ToString()))
        //    {
        //        //项目负责人(李勇账号)
        //        //var PerformanceslistAdmin = db.Performances.Where(x => x.type != 1 && x.State >= 4 && x.TableType == 4).OrderBy(x => x.PerformanceDataTime).ToList();
        //        //获取所有项目负责人
        //        List<string> ProjectHeadUserIdList = _db.Project.Where(x => x.Delete != true).Select(z => z.HeadUserId).ToList();
        //        List<int> ids150407 = new List<int>();
        //        List<int> noids150407 = new List<int>();
        //        foreach (var item in ProjectHeadUserIdList)
        //        {
        //            if (!string.IsNullOrWhiteSpace(item))
        //            {
        //                var itemid = Convert.ToInt32(item);
        //                string roleids = _db.Users.FirstOrDefault(x => x.Id == itemid).RoleId;
        //                if (roleids != "")
        //                {
        //                    int[] ids = stringtoints(roleids);
        //                    List<Role> numbers = (List<Role>)_db.Role.Where(x => ids.Contains(x.Id)).ToList();
        //                    string rolenumbers = string.Empty;
        //                    foreach (var items in numbers)
        //                    {
        //                        rolenumbers += items.RoleNumber;
        //                    }
        //                    //权限一
        //                    if (rolenumbers.Contains(ModuleAuthorityCode.SitePerformanceJudgment1.ToString()))
        //                    {
        //                        ids150407.Add(Convert.ToInt32(item));
        //                    }
        //                    else
        //                    {
        //                        noids150407.Add(Convert.ToInt32(item));
        //                    }
        //                }
        //            }
        //        }
        //        var Performanceslistno150407 = _db.Performances.Where(x => noids150407.Contains(x.PerformanceUserID) && x.State >= 4 && x.type != 1 && x.TableType == 4).ToList();
        //        if (Performanceslistno150407.Any())
        //        {
        //            foreach (var item in Performanceslistno150407)
        //            {
        //                PerformancesList.Add(item);
        //            }
        //        }
        //        var Performanceslistids150407 = _db.Performances.Where(x => ids150407.Contains(x.PerformanceUserID) && x.State >= 1 && x.type != 1 && x.TableType == 4).ToList();
        //        if (Performanceslistno150407.Any())
        //        {
        //            foreach (var item in Performanceslistids150407)
        //            {
        //                PerformancesList.Add(item);
        //            }
        //        }
        //    }
        //    //绩效管理者
        //    if (rolestr.Contains(ModuleAuthorityCode.PerformanceManagementAuthority.ToString()))
        //    {
        //        //获取所有的绩效表不包括现场表
        //        var PerformanceslistAdmin = _db.Performances.Where(x => x.TableType != 4 && x.State >= 1 && x.type != 1).ToList();
        //        foreach (var item in PerformanceslistAdmin)
        //        {
        //            PerformancesList.Add(item);
        //        }
        //    }
        //    //分支部门领导人反射出部门中的绩效考核,和总结
        //    var departmentlist = departmentOkorNo(Userid);
        //    if (departmentlist.Any())
        //    {
        //        int[] Departids = departmentlist.Select(x => x.Id).ToArray();
        //        //分管领导下所有成员
        //        var userall = UserAllByDepartmentId(Departids);
        //        string ids = string.Join(",", userall.Select(x => x.Id));

        //        if (ids != "")
        //        {
        //            string sql = $"SELECT * FROM `performances` WHERE PerformanceUserID in({ids}) and TableType !=4  and type !=1 and State >=4    ORDER BY PerformanceDataTime DESC";
        //            var userlist = _db.Performances.FromSqlRaw(sql).ToList();
        //            foreach (var item in userlist)
        //            {
        //                PerformancesList.Add(item);
        //            }
        //        }
        //        ////分管领导下的部长
        //        ////状态负责人的状态一
        //        string PartOwnerids = string.Join(",", PartOwnerByIds(ids).Select(x => x.PartOwner));
        //        if (PartOwnerids != "")
        //        {
        //            string PartOwneridssql = $"SELECT * FROM `performances` WHERE PerformanceUserID in({PartOwnerids}) and TableType !=4  and type !=1 and State =2    ORDER BY PerformanceDataTime DESC";
        //            var PartOwneridsuserlist = _db.Performances.FromSqlRaw(PartOwneridssql).ToList();
        //            foreach (var item in PartOwneridsuserlist)
        //            {
        //                PerformancesList.Add(item);
        //            }
        //        }

        //    }
        //    //负责人有可能是多个部门的负责人
        //    var deparmentId = departmentParOkorNo(Userid);
        //    if (deparmentId.Any())
        //    {
        //        //除去现场表和计划表 还有自己的的的绩效和总结 
        //        string depaid = string.Join(",", deparmentId.Select(x => x.Id));
        //        int[] ids = stringtoints(depaid);
        //        var Allusers = _db.Users.Where(x => ids.Contains(x.DepartmentId)).ToList();
        //        string Userids = string.Join(",", Allusers.Select(x => x.Id));
        //        int[] allids = stringtoints(Userids);
        //        var alluers1 = _db.Performances.Where(x => allids.Contains(x.PerformanceUserID) && x.type == 4 && x.TableType != 4 && x.State >= 2).ToList();
        //        var alluers2 = _db.Performances.Where(x => allids.Contains(x.PerformanceUserID) && x.type == 2 && x.TableType != 4 && x.State >= 1).ToList();
        //        foreach (var item in alluers1)
        //        {
        //            PerformancesList.Add(item);
        //        }
        //        foreach (var item in alluers2)
        //        {
        //            PerformancesList.Add(item);
        //        }
        //    }
        //    //数据去重复并且按照时间排序
        //    return Unino.ListRepetitionPerformances(PerformancesList);
        //}

        ///// <summary>
        ///// 用户未批阅的数据条数 
        ///// </summary>
        ///// <param name="performances"></param>
        ///// <param name="number"></param>
        //public void Ispanding(List<Performances> performances, out int number)
        //{
        //    var author = HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];
        //    int Userid = Convert.ToInt32(TokenManage.GetTokenValues(author)[0].Value);
        //    number = 0;
        //    //修改用户或获取的权限
        //    string OperatIdquanxian = Isquanxyi(Userid).ToString();
        //    if (OperatIdquanxian == "Admin")
        //    {
        //        return;
        //    }
        //    // 判断是否是项目负责人
        //    List<Project> OperatIdHead = ProjectHeadUserIdById(Userid);
        //    foreach (var item in performances)
        //    {
        //        var state = item.State;
        //        //现场表
        //        if (item.TableType == 4)
        //        {
        //            // 判断是否是项目负责人
        //            // List<Project> OperatIdHead = ProjectHeadUserIdById(Userid);
        //            var news = _db.Performances.Where(x => x.Id == item.Id).FirstOrDefault();
        //            //var Usersonly = db.Users.FirstOrDefault(x => x.Id == news.PerformanceUserID);
        //            //表用户所获取的权限
        //            string newsRoleId = Isquanxyi(news.PerformanceUserID).ToString();
        //            //表用户是否为负责人
        //            List<Project> newsHead = ProjectHeadUserIdById(news.PerformanceUserID);
        //            ////修改用户是否为负责人
        //            //权限一
        //            if (newsRoleId == "1")
        //            {
        //                if (OperatIdquanxian == "2")
        //                {
        //                    number = number + 1;
        //                }
        //            }
        //            //表用户为项目负责人
        //            else if (newsHead.Any())
        //            {
        //                //权限1 上级部门编写
        //                if (state == 1 && OperatIdquanxian == "1")
        //                {
        //                    number = number + 1;
        //                }
        //                //权限2
        //                if (state == 4 && OperatIdquanxian == "2")
        //                {
        //                    number = number + 1;
        //                }
        //            }
        //            //表用户为普通员工
        //            else
        //            {
        //                //判断修改人员是否是项目负责人
        //                if (OperatIdHead.Any())
        //                {
        //                    foreach (var items in OperatIdHead)
        //                    {
        //                        if (items.MemberId != null)
        //                        {
        //                            if (state == 1 && items.MemberId.Contains(news.PerformanceUserID.ToString()))
        //                            {
        //                                number = number + 1;
        //                            }
        //                        }
        //                    }
        //                }
        //                if (state == 4 && OperatIdquanxian == "2")
        //                {
        //                    number = number + 1;
        //                }
        //            }
        //        }
        //        //员工表或中高层表
        //        else
        //        {
        //            ////状态一运营综合部

        //            var deparment = _db.Department.FirstOrDefault(y => y.Id == _db.Users.FirstOrDefault(x => x.Id == item.PerformanceUserID).DepartmentId);
        //            //绩效表
        //            if (item.type == 4)
        //            {
        //                if (state == 1 && OperatIdquanxian == "YY")
        //                {
        //                    number = number + 1;
        //                }
        //                //  运营综合部打分时高层表显示 条数不变item.TableType!=2
        //                if (state == 2 && deparment.PartOwner == Userid && item.TableType != 2)
        //                {
        //                    number = number + 1;
        //                }
        //                if (state == 4 && deparment.LeaderShip == Userid)
        //                {
        //                    number = number + 1;
        //                }
        //            }
        //            //总结表
        //            else
        //            {
        //                if (state == 1 && deparment.PartOwner == Userid)
        //                {
        //                    number = number + 1;
        //                }
        //                if (state == 4 && deparment.LeaderShip == Userid)
        //                {
        //                    number = number + 1;
        //                }
        //            }
        //        }
        //    }
        //}

        //#region string转int[]
        //public int[] stringtoints(string values)
        //{

        //    string[] valuesToint = values.Split(',');
        //    List<int> idslist = new List<int>();
        //    for (int i = 0; i < valuesToint.Length; i++)
        //    {
        //        if (!(string.IsNullOrWhiteSpace(valuesToint[i])))
        //        {
        //            idslist.Add(Convert.ToInt32(valuesToint[i]));
        //        }
        //    }
        //    return idslist.ToArray(); ;
        //}
        //#endregion

        //#region 获取是否是分支领导
        ///// <summary>
        ///// 获取是否是分支部门负责人
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public List<Department> departmentOkorNo(int id)
        //{
        //    return _db.Department.Where(x => x.LeaderShip == id && x.Delete == false).ToList();//获取是否是部门负责人
        //}
        //#endregion

        //#region 根据部门Id获取部门成员
        ///// <summary>
        ///// 根据部门Id获取成员
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public List<Users> UserAllByDepartmentId(int[] id)
        //{
        //    return _db.Users.Where(x => id.Contains(x.DepartmentId)).ToList();
        //}
        //#endregion

        //#region 获取数组内有负责人
        //public List<Department> PartOwnerByIds(string ids)
        //{
        //    string sql = $"SELECT * FROM `department` WHERE PartOwner in({ids})";
        //    return _db.Department.FromSqlRaw(sql).ToList();
        //}
        //#endregion

        //#region 获取是否是部门负责人
        ///// <summary>
        ///// 获取是否是部门负责人
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //public List<Department> departmentParOkorNo(int id)
        //{
        //    return _db.Department.Where(x => x.PartOwner == id && x.Delete == false).ToList();//获取是否是部门负责人
        //}
        //#endregion

        //#region 判断人员是否拥有特殊权限
        //public string Isquanxyi(int id)
        //{
        //    string Roleid = _db.Users.FirstOrDefault(x => x.Id == id).RoleId;
        //    //string Number = db.Role.FirstOrDefault(x => x.Id.ToString() == Roleid).RoleNumber;
        //    string str = $"select * from role WHERE id in ({Roleid}) ";
        //    var Roles = _db.Role.FromSqlRaw(str).ToList();
        //    string Number = string.Join(",", Roles.Select(x => x.RoleNumber));
        //    if (Number.Contains("Admin"))
        //    {
        //        return "Admin";
        //    }
        //    //权限1
        //    if (Number.Contains(ModuleAuthorityCode.OperationPerformanceManagement))
        //    {
        //        return "YY";
        //    }
        //    else if (Number.Contains(ModuleAuthorityCode.SitePerformanceJudgment1))
        //    {
        //        return "1";
        //    }
        //    else if (Number.Contains(ModuleAuthorityCode.SitePerformanceJudgment2))
        //    {
        //        return "2";
        //    }
        //    //超级小权限
        //    else if (Number.Contains(ModuleAuthorityCode.PerformanceManagementAuthority))
        //    {
        //        return "Admin2";
        //    }
        //    return "N";
        //}
        //#endregion

        //#region 判断是否是项目负责人
        //public List<Project> ProjectHeadUserIdById(int id)
        //{
        //    return _db.Project.Where(z => z.HeadUserId == id.ToString() && z.Delete != true).ToList();
        //}
        //#endregion
    }
    /// <summary>
    /// List去重
    /// </summary>
    public static class Unino
    {
        /// <summary>
        /// 去掉Performances表中重复的数据根据Id
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static List<Performances> ListRepetitionPerformances(List<Performances> list)
        {
            var perormlist = (List<Performances>)list.AsQueryable().DistinctBy(s => s.Id).ToList();
            return perormlist.OrderByDescending(x => x.PerformanceDataTime).ToList();
        }

        public static List<Users> ListRepetitionUsers(List<Users> list)
        {
            return list.AsQueryable().DistinctBy(s => s.Id).ToList();
        }
        public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }

    }
}
